package in.edupack.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * This class demonstrate a simple jdbc connection to remote mysql database
 * @author Bibek
 * command line arguments sample <example.com><dbName><dbUser><dbPassword>
 */
public class MySqlConnectionDemo {
	private static Connection con=null;
	private static String dbUrl = null;
	private static String dbName = null;
	private static String dbUser = null;
	private static String dbPassword = null;

	public static void main(String[] args) throws SQLException {
		
		//set db parameter to variables received form command prompt
		if (args.length < 3){
			System.out.println("Pass four command line arguemnts <dbUrl><dbName><dbUser><dbPasswod>");
			System.exit(2);
		}else
		{
		   MySqlConnectionDemo.dbUrl = args[0];
		   MySqlConnectionDemo.dbName = args[1];
		   MySqlConnectionDemo.dbUser = args[2];
		   MySqlConnectionDemo.dbPassword = args[3];
		}
		
		System.out.println(MySqlConnectionDemo.getRemoteMySQLConnection());
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery("select * from student");
		while (rs.next())
		{
			System.out.println("Id "+rs.getString("id")+" Name "+rs.getString("name") + " Phone "+rs.getString("phone") + 
					" Address " + rs.getString("address"));
		}
		
		con.close();
		
	}
	
	
	
	public static Connection getRemoteMySQLConnection(){
			try {
				 Class.forName("com.mysql.jdbc.Driver");
				 String connectionUrl = "jdbc:mysql://"+dbUrl+"/"+dbName;
				 System.out.println(connectionUrl);
		         con=DriverManager.getConnection(connectionUrl,dbUser,dbPassword);
		     	}catch(Exception e){System.out.println(e.getMessage());}
		   return con;
	}
}
